package org.newcih.activiti.activitiInAction.chapter2;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.newcih.activiti.test.BaseActivitiTest;

import java.util.HashMap;
import java.util.Map;

public class SayHelloToLeaveTest extends BaseActivitiTest {

    @Before
    public void deploy() {
        deploy("activiti/Leader.bpmn20.xml");
    }

    @Test
    public void list() {
        repositoryService.createDeploymentQuery().list().forEach(deployment ->
                System.out.println("id = " + deployment.getId() + " , name=" + deployment.getName())
        );
    }

    @Test
    public void delete() {
        // 级联删除所有流程
        repositoryService.createDeploymentQuery().list().stream()
                .map(Deployment::getId)
                .forEach(id -> repositoryService.deleteDeployment(id, true));

        int num = repositoryService.createDeploymentQuery().list().size();
        if (num == 0) {
            System.out.println("所有已部署流程都已回收");
        } else
            System.out.println("目前存活流程数 " + num);
    }

    @Test
    public void testStartProcess() {
//        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().singleResult();
//        Assert.assertEquals(processDefinition.getKey(), "SayHelloToLeave");
        repositoryService.createProcessDefinitionQuery().list().forEach(System.out::println);


        Map<String, Object> variables = new HashMap<>();
        variables.put("applyUser", "employee1");
        variables.put("days", 3);
        ProcessInstance instance = runtimeService.startProcessInstanceByKey("SayHelloToLeave", variables);
        Assert.assertNotNull(instance);

        Task taskOfDeptLeader = taskService.createTaskQuery().taskCandidateGroup("deptLeader").singleResult();
        Assert.assertNotNull(taskOfDeptLeader);
        Assert.assertEquals("领导审批", taskOfDeptLeader.getName());

        taskService.claim(taskOfDeptLeader.getId(), "leaderUser");
        variables = new HashMap<>();
        variables.put("approved", true);
        taskService.complete(taskOfDeptLeader.getId(), variables);

        taskOfDeptLeader = taskService.createTaskQuery().taskCandidateGroup("deptLeader").singleResult();
        Assert.assertNull(taskOfDeptLeader);

        long count = historyService.createHistoricProcessInstanceQuery().finished().count();
        Assert.assertEquals(1, count);
    }
}
